package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 *  商品种类
 *  @author Rose
 *  @date 2020/1/8
 * create by Rose on 2020/1/8
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BrandService {

    @Autowired
    private BrandMapper brandMapper ;


    /**
     *
     * 分页查询品牌
     *
     *
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        // 分页
        PageHelper.startPage(page,rows);

        // 构造查询条件
        Example example = new Example(Brand.class);
        // 排序
        if(StringUtils.isNotBlank(sortBy)){
            // id desc ; id asc
            example.setOrderByClause(sortBy +  ( desc ? " DESC " : " ASC "));
        }
        // 查询
        if(StringUtils.isNotBlank(key)) {
            example.createCriteria().orLike("name", "%" + key + "%" )
                    .orEqualTo("letter", key.toUpperCase());
        }

        List<Brand> list = this.brandMapper.selectByExample(example) ;
        if(CollectionUtils.isEmpty(list)){
            throw new LeYouException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 解析分页返回结果
        // 创建PageInfo
        PageInfo<Brand> info = new PageInfo<>(list);
        // 返回分页结果
        return  new PageResult<>(info.getTotal(), Long.valueOf(info.getPages()), list);
    }

    /**
     *  保存品牌
     *
     *
     *   通用Mapper 只能处理单表， 也就是Brand 的数据，因此我们手动编写一个方法及sql, 实现中间表的新增。
     *
     * @param brand
     * @param cids
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(Brand brand, List<Long> cids) {

        brand.setId(null);
        // 新增品牌
        int count = this.brandMapper.insert(brand);
        if(count != 1){
            throw new LeYouException(ExceptionEnum.PRICE_CANNOT_BE_NULL);
        }
        // 新增品牌和分类的中间表
        for(Long cid : cids){
            count  = this.brandMapper.insertCategoryBrand(cid, brand.getId());
            if(count != 1){
                throw new LeYouException(ExceptionEnum.PRICE_CANNOT_BE_NULL);
            }
        }
    }


    /**
     *
     *  根据id删除品牌
     *
     * @param id
     */
    public void deleteById(Long id) {

        int result = this.brandMapper.deleteByPrimaryKey(id);

        if(result != 1 ){
            throw new LeYouException(ExceptionEnum.BRAND_DELETE_ERROR);
        }
        // 删除关联的表的信息
        // 先查询，再挨个删除
        int idelete = this.brandMapper.deleteCategoryBrand(id);

        //
        log.info("删除关联表的相关数据： "+ idelete);
    }

    /**
     *  根据主键id, 查询品牌
     *
     * @param id
     * @return
     */
    public Brand queryById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new LeYouException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    /**
     * @param cid
     * @return
     */
    public List<Brand> queryBrandBycid(Long cid) {

        if (cid == null) {
            throw new LeYouException(ExceptionEnum.BRAND_CID_NOT_FOUND);
        }

        List<Brand> brandList = brandMapper.queryByCategoryId(cid);

        if (CollectionUtils.isEmpty(brandList)) {
            throw new LeYouException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brandList;
    }

    /**
     * 根据品牌ids 进行列表查询
     *
     * @param ids
     * @return
     */
    public List<Brand> queryBrandByIds(List<Long> ids) {

        List<Brand> brandList = this.brandMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LeYouException(ExceptionEnum.BRAND_LIST_NOT_FOUND);
        }
        return brandList;
    }
}
